package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.admin.service.IPushService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.SysPushMessageMapper;
import com.ee.chat.common.entity.SysPushMessage;
import com.ee.chat.common.service.IPushMessageService;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Shane
 * @Date 2020/3/13 14:43
 */
@Service
public class PushServiceImpl implements IPushService {
    @Resource
    SysPushMessageMapper sysPushMessageMapper;
    @Resource
    IOperationService operationService;
    @Resource
    IPushMessageService pushMessageService;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit, String keyword) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(keyword)){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/push/viewList")){
                data.put("datas", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<SysPushMessage> iPage = sysPushMessageMapper.list(p, keyword);

        data.put("datas", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "获取系统推送数据列表");

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(HttpServletRequest request, Integer msgType, Integer userId, String title, String content) throws Exception {
        Map<String, String> push = new HashMap<>();
        push.put("title", title);
        push.put("content", content);
        push.put("type", "0");

        if(msgType == 0){
            pushMessageService.pushGroupMessage(title, content, push);

            operationService.addOperationLog(request, "发布"+title+"公告");
        }else{
            pushMessageService.pushGeneralMessage(userId, push);

            operationService.addOperationLog(request, "向"+userId+"推向"+title+"消息");
        }

        return Result.returnSuccess(null);
    }
}
